package com.banciyuan.bcywebview.biz.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.SpaceApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.setting.bansetting.BlockListActivity;
import com.banciyuan.bcywebview.biz.privatemessage.PrivateMessageSettingActivity;
import com.banciyuan.bcywebview.utils.cache.CacheUtils;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.NetUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.google.gson.Gson;
import com.tencent.tauth.Tencent;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.AppSetting;

/**
 * Created by hy on 2015/4/30.
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {

    private TextView tvCacheSize;
    private TextView tvPrivateSettingStatus;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private View view;
    public static final int CACHESIZE = 200;

    private ImageLoader imageLoader;
    private File imageDirectory;
    private AppSetting appSetting;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String size = (String) msg.obj;
            tvCacheSize.setText(size);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = View.inflate(this, R.layout.activity_setting, null);
        setContentView(view);
        initActionbar();
        initUi();
        initArgs();
        initAction();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initArgs() {
        new Thread() {
            @Override
            public void run() {
                String size = getCacheSize();
                Message message = Message.obtain();
                message.obj = size;
                message.what = CACHESIZE;
                handler.sendMessage(message);
            }
        }.start();
    }


    private String getCacheSize() {
        imageLoader = ImageLoader.getInstance();
        imageDirectory = imageLoader.getDiskCache().getDirectory();
        long imageDirectoryLength = 0;
        if (imageDirectory.exists()) {
            imageDirectoryLength = CacheUtils.getFilesSize(imageDirectory);
        }
        long length = imageDirectoryLength;
        String size = CacheUtils.getFormatSize(length);
        return size;
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.setting));
    }

    @Override
    protected void initUi() {
        tvCacheSize = (TextView) findViewById(R.id.tv_cache_size);
        tvPrivateSettingStatus = (TextView) findViewById(R.id.tv_private_setting_status);
    }

    @Override
    protected void initAction() {
        findViewById(R.id.rl_clear).setOnClickListener(this);
        findViewById(R.id.rl_logout).setOnClickListener(this);
        findViewById(R.id.rl_feedback).setOnClickListener(this);
        findViewById(R.id.rl_blcoksetting).setOnClickListener(this);
        findViewById(R.id.rl_account_relevance).setOnClickListener(this);
        findViewById(R.id.rl_account_private).setOnClickListener(this);
        findViewById(R.id.rl_main_setting).setOnClickListener(this);
        findViewById(R.id.rl_ask_setting).setOnClickListener(this);
        findViewById(R.id.rl_night_setting).setOnClickListener(this);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + SpaceApi.getSettings();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairs.add(new BcyPair(HttpUtils.STYPE, "message"));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    if (StatusCodeUtils.dealStatusCode(response, SettingActivity.this)) {
                        JSONObject jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        appSetting = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), AppSetting.class);
                        renderData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        };

        OnErrorProxy errorProxy = new OnErrorProxy(onError, onSucc, url, this, map);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, errorProxy);
        VolleyQueue.getRquest(this).add(requestParam);
    }

    private void renderData() {
        String type = appSetting.getMessage().getSend();
        if (StringUtil.notNullEqual(type, "all")) {
            tvPrivateSettingStatus.setText(getString(R.string.privatemessage_select_two));
        } else {
            tvPrivateSettingStatus.setText(getString(R.string.privatemessage_select_one));
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rl_clear:
                doClear();
                break;
            case R.id.rl_logout:
                showLogout();
                break;
            case R.id.rl_feedback:
                gotoUtil.gotoAct(this, FeedBackActivity.class);
                break;
            case R.id.rl_blcoksetting:
                gotoUtil.gotoAct(this, BlockListActivity.class);
                break;
            case R.id.rl_account_relevance:
                gotoUtil.gotoAct(this, UserRelevanceActivity.class);
                break;
            case R.id.rl_account_private:
                gotoPrivateMessage();
                break;
            case R.id.rl_main_setting:
                gotoUtil.gotoAct(this, MainSettingActivity.class);
                break;
            case R.id.rl_ask_setting:
                gotoUtil.gotoAct(this, AskSettingActivity.class);
                break;
            case R.id.rl_night_setting:
                gotoUtil.gotoAct(this, NightSettingActivity.class);
                break;
        }
    }

    private void gotoPrivateMessage() {
        Intent intent = new Intent(this, PrivateMessageSettingActivity.class);
        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, appSetting);
        startActivity(intent);
    }

    private void showLogout() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.confirm_exit_warn))
                .setActionString(getString(R.string.confirm_exit))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doLogout();
                    }
                })
                .create().show();
    }


    private void doClear() {
        ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
        builder.setDescString(getString(R.string.confirmclearcache))
                .setActionString(getString(R.string.clear_cache))
                .setCancelString(getString(R.string.mydialog_cancel))
                .setActionClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new Thread() {
                            @Override
                            public void run() {
                                SPHelper.putString(SettingActivity.this, SPConstant.SPNAME_INITBACKURL, SPConstant.URL, "");
                                SPHelper.putInt(SettingActivity.this, SPConstant.SPNAME_INITBACKGROUND, SPConstant.VERSION, 0);
                                RequestQueue queue = VolleyQueue.getRquest(SettingActivity.this);
                                queue.getCache().clear();
                                CacheUtils.deleteFilesByDirectory(getCacheDir());
                                CacheUtils.deleteFilesByDirectory(getExternalCacheDir());
                                CacheUtils.deleteFilesByDirectory(imageDirectory);
                                ImageLoader.getInstance().clearDiskCache();
                                ImageLoader.getInstance().clearMemoryCache();
                            }
                        }.start();
                        doPop();
                    }
                })
                .create().show();
    }

    private void doPop() {
        View contentView = View.inflate(this, R.layout.pop_clear_cache, null);
        final PopupWindow mPopWindow = new PopupWindow(contentView,
                -1, -1,
                true);
        mPopWindow.setContentView(contentView);
        final ProgressBar pbIng = (ProgressBar) contentView.findViewById(R.id.pb_ing);
        final ImageView ivDone = (ImageView) contentView.findViewById(R.id.iv_done);
        final TextView tvDesc = (TextView) contentView.findViewById(R.id.tv_desc);
        mPopWindow.setOutsideTouchable(false);
        mPopWindow.showAtLocation(view, Gravity.LEFT + Gravity.TOP,
                0, 0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                pbIng.setVisibility(View.INVISIBLE);
                ivDone.setVisibility(View.VISIBLE);
                tvDesc.setText(getString(R.string.cache_has_clear));
            }
        }, 1200);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (null != mPopWindow && mPopWindow.isShowing()) {
                    mPopWindow.dismiss();
                    tvCacheSize.setText("0.0B");
                }
            }
        }, 1800);
    }


    private void doLogout() {
        if (!UserDataHelper.ifLogin(this) || !NetUtils.checkNetwork(this)) {
            MyToast.show(this, getString(R.string.network_something_wrong));
            return;
        }
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    UserDataHelper.Logout(SettingActivity.this, new UserDataHelper.ClearAliasCallBack() {
                        @Override
                        public void doclear() {
                            if (!SettingActivity.this.isFinishing()) {
                                gotoUtil.replaceLogin(SettingActivity.this);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                try {
                    UserDataHelper.Logout(SettingActivity.this, new UserDataHelper.ClearAliasCallBack() {
                        @Override
                        public void doclear() {
                            if (!SettingActivity.this.isFinishing()) {
                                gotoUtil.replaceLogin(SettingActivity.this);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Tencent.createInstance(MyConstants.QQ_LOGIN_APP_ID, getApplicationContext()).logout(
                getApplicationContext());

        if (!CommonApiUtils.doLogOut(this, VolleyQueue.getRquest(this), onSuccess, onError)) {
            MyToast.show(this, getString(R.string.network_something_wrong));
        }
    }
}
